﻿using Models;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class D_Teacher
    {
        public int Add_custom(List<Teacher> teachers)
        {
            var res = -1;
            try
            {
                string sqlteacher = 
                
                            "if not exists (select 1 from Teacher where teacher_uname = @teacher_uname)" +
                            "insert into Teacher(teacher_name, teacher_uname, pwd, depart, info) " + 
                            "values( @teacher_name, @teacher_uname, @pwd,@depart,@info)" +
                            "else update Teacher set teacher_name=@teacher_name, pwd=@pwd, " + 
                            "depart=@depart, info=@info where  teacher_uname = @teacher_uname";
                
                SqlParameter[] sps = new SqlParameter[5];

                foreach (var teacher in teachers)
                {
                    sps[0] = new SqlParameter("@teacher_uname", teacher.teacher_uname);
                    sps[1] = new SqlParameter("@teacher_name", teacher.teacher_name);
                    sps[2] = new SqlParameter("pwd", "123");
                    sps[3] = new SqlParameter("@depart", teacher.depart);
                    sps[4] = new SqlParameter("@info", teacher.info);
                    SqlDbHelper.ExecuteNonQuery(sqlteacher, System.Data.CommandType.Text, sps);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return res;
        }


        public List<Teacher> GetList(int grade, int major_id)
        {
            var list = Sugar_helper.Db.Queryable<Teacher>()
                .Where(tea=>SqlFunc.Subqueryable<Tutor>().Where(tut=>tut.grade==grade && tut.major_id==major_id && tea.teacher_id==tut.teacher_id).Any()).ToList();

            return list;
        }
        public bool Login_sugar(Models.Teacher m_teacher)//验证老师登录信息的函数
        {

            var teachers = Sugar_helper.Db.Queryable<Teacher>().Where(t => t.teacher_uname == m_teacher.teacher_uname && t.pwd == m_teacher.pwd).ToList();
            if (teachers.Count == 0) return false;
            
            log_info.Server_Time = Sugar_helper.Db.GetDate();

            log_info.teacher = teachers[0];
            var sys_config = Sugar_helper.Db.Queryable<Sys_config>().ToList();

            if (sys_config.Count > 0)
            {
                log_info.Sys_Config.tearch_choice = sys_config[0].tearch_choice;
                log_info.Sys_Config.group_choice = sys_config[0].group_choice;
            }

            return true;
        }
        public List<Teacher> GetList()
        {
            var list = Sugar_helper.Db.Queryable<Teacher>().ToList();
            return list;
        }
    }
}
